<!-- eslint-disable vue/no-dupe-keys -->
<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <!-- <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>

        <span>|</span> -->

        <el-page-header :content="`${id ? '编辑企业' : '添加企业'}`" @back="$router.back()" />

      </div>

      <div class="right">
        黑马程序员
      </div>

    </header>

    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="ruleForm" label-width="100px" :model="addForm" :rules="addRules">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" placeholder="请输入企业名称" />
            </el-form-item>

            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" placeholder="请输入法人" />
            </el-form-item>

            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" placeholder="请输入注册地址" />
            </el-form-item>

            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode" placeholder="请选择所在行业">
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :label="item.industryName"
                  :value="item.industryCode"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="营业执照" prop="businessLicenseId">
              <el-upload
                :on-preview="handlePreview"
                :http-request="uploadRequest"
                action="#"
                :before-upload="beforeUpload"
                :limit="3"
              >
                <el-button size="small" type="primary">上传文件</el-button>
                <div slot="tip" class="el-upload__tip">支持扩展名:.png .jpg .jpeg文件，文件不超过5M</div>
              </el-upload>

            </el-form-item>
          </el-form>

        </div>

      </div>
      <div class="form-container">
        <div class="title">联系人信息</div>
        <div class="form">
          <el-form ref="contactForm" label-width="100px" :model="contactForm" :rules="contactRules">
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="contactForm.contact" />
            </el-form-item>

            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="contactForm.contactNumber" />
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>

    <footer class="add-footer">
      <div class="btn-container">
        <el-button>重置</el-button>

        <el-button type="primary" @click="confirmSubmit">确定</el-button>

      </div>

    </footer>
    <el-dialog :visible.sync="dialogVisible">
      <el-image :src="addForm.businessLicenseUrl" fit="cover" width="100" height="100">
        <el-tooltip class="item" effect="dark" content="点击查看图片" placement="top">
          <i
            class="el-icon-view"
            style="position: absolute; right: 5px; bottom: 5px; font-size: 20px; cursor: pointer;"
          />
        </el-tooltip>
      </el-image>
    </el-dialog>

  </div>

</template>

<script>
import { createExterpriseAPI, getEnterpriseDetailAPI, getIndustryAPI, updateExterpriseAPI, uploadAPI } from '@/api/park'

export default {
  data() {
    return {
      addForm: {
        name: '', // 企业名称
        legalPerson: '', // 法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 所在行业
        businessLicenseUrl: '', // 营业执照url
        businessLicenseId: '' // 营业执照id
      },
      contactForm: {
        contact: '', // 企业联系人
        contactNumber: '' // 联系人电话
      },
      industryList: [], // 行业列表
      // 企业信息验证规则
      addRules: {
        name: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
        legalPerson: [{ required: true, message: '请输入法人', trigger: 'blur' }],
        registeredAddress: [{ required: true, message: '请输入注册地址', trigger: 'blur' }],
        industryCode: [{ required: true, message: '请选择所在行业', trigger: 'change' }],
        businessLicenseUrl: [{ required: true, message: '请上传营业执照', trigger: 'blur' }]
      },
      // 联系人信息验证规则
      contactRules: {
        contact: [{ required: true, message: '请输入企业联系人', trigger: 'blur' }],
        contactNumber: [
          { required: true, message: '请输入联系人电话', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (/^1[3-9]\d{9}$/.test(value)) {
                callback()
              } else {
                callback(new Error('请输入正常的手机号'))
              }
            }, trigger: 'blur' }
        ]
      },
      dialogVisible: false, // 控制弹窗的显示
      previewImage: '' // 预览的图片地址

    }
  },
  computed: {
    // eslint-disable-next-line vue/no-dupe-keys
    id() {
      return this.$route.query.id
    }
  },
  mounted() {
    if (this.id) {
      this.getEnterpriseDetail()
    }
    this.getIndustryList()
  },
  methods: {
    // 获取企业所属行业列表
    async getIndustryList() {
      const res = await getIndustryAPI()
      this.industryList = res.data
    },
    // 获取企业详情
    async getEnterpriseDetail() {
      const res = await getEnterpriseDetailAPI(this.id)
      const { businessLicenseId, businessLicenseUrl, contact, contactNumber, industryCode, legalPerson, name, registeredAddress } = res.data
      this.addForm = { businessLicenseId, businessLicenseUrl, industryCode, legalPerson, name, registeredAddress }
      this.contactForm = { contact, contactNumber }
    },
    // 上传图片
    async uploadRequest(data) {
      const file = data.file
      const formData = new FormData()// 用于构建表单数据,将文件和一些附加信息（类型）一起发送到服务器
      formData.append('file', file)// 追加文件到 FormData
      formData.append('type', 'businessLicense')// 1、企业营业执照businessLicense2、租赁合同附件contract
      const res = await uploadAPI(formData)
      // 赋值表单数据
      this.addForm.businessLicenseId = res.data.id
      this.addForm.businessLicenseUrl = res.data.url
      console.log('上传成功', this.addForm)
      this.$refs.ruleForm.validateField('businessLicenseUrl') // 手动触发验证
    },
    // 上传前的钩子函数 校验
    beforeUpload(file) {
      const allowImgType = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!allowImgType) {
        this.$message.error('上传合同图片只能是 PNG/JPG/JPEG 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传合同图片大小不能超过 5MB!')
      }
      return allowImgType && isLt5M
    },
    // 点击预览图片
    handlePreview(file) {
      this.previewImage = file.url // 设置预览图片地址
      this.dialogVisible = true // 显示弹窗
    },
    // 确认提交
    confirmSubmit() {
      this.$refs.ruleForm.validate(async ok => {
        if (ok) {
          this.$refs.contactForm.validate(async ok => {
            if (ok) {
              // 提交数据
              const payload = {
                ...this.addForm,
                ...this.contactForm,
                id: this.id
              }
              if (this.id) {
                await updateExterpriseAPI(payload)
              } else {
                await createExterpriseAPI(payload)
              }

              this.$router.back()
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }
      .arrow{
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left:20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form{
          display: flex;
          flex-wrap: wrap;
          .el-form-item{
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
